<template>
  <a-tree-select
    v-model="inputValue"
    :style="{ width: width ? `${width}px` : '100%' }"
    :dropdownStyle="dropdownStyle"
    show-search
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    :tree-data="treeData"
    :replaceFields="replaceFields"
    :placeholder="searchPlaceholder"
    treeNodeFilterProp="title"
    allow-clear
    :treeDefaultExpandAll="true"
    :treeCheckable="true"
    :disabled="disabled"
    @change="handleChange"
  />
</template>

<script>
import { managementAttachmentDirectoryTreeList } from "@/api/directory";
export default {
  /**
   * 【文档目录】树选择组件，多选
   */
  name: "DirectoryTreeMultiple",
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    value: {
      type: [Array],
      default: () => {
        return [];
      },
    },
    // 占位符
    placeholder: {
      type: String,
      default: "",
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 宽度，默认100%
    width: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      // treeData 中对应的字段
      replaceFields: {
        children: "children",
        title: "directoryName",
        key: "id",
        value: "id",
      },
      // 数据源
      treeData: [],
      dropdownStyle: {
        zIndex: 3000,
      },
    };
  },
  computed: {
    searchPlaceholder: {
      get() {
        return this.placeholder ? `请选择${this.placeholder}` : `请选择`;
      },
      set() {},
    },
    inputValue: {
      get() {
        return this.value;
      },
      set(val) {},
    },
  },
  created() {
    // 加载文档目录
    const params = {
      directoryName: "",
    };
    managementAttachmentDirectoryTreeList(params).then((res) => {
      this.treeData = this.arrayToTree(res, 0);
    });
  },
  methods: {
    arrayToTree(data, rootId) {
      const arr = data.filter((item) => {
        return item.parentId === rootId;
      });
      return arr.map((item) => {
        item.children = this.arrayToTree(data, item.id);
        return item;
      });
    },
    handleChange(value, label, extra) {
      this.$emit("change", value, label);
    },
  },
};
</script>

<style lang="scss" scoped></style>
